﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;

using Microsoft.WowAddonStudio.Lua.Model;
using Microsoft.WowAddonStudio.Lua.Support;

namespace Microsoft.WowAddonStudio.Lua.Loaders
{
    /// <summary>
    /// A <see cref="DocumentationLoader"/> that loads the <see cref="Documentation"/> from
    /// XML files found in a directory.
    /// </summary>
    public abstract class XmlDocumentationLoader : DocumentationLoader
    {
        private static readonly XmlDocumentationSerializer xmlDocumentationSerializer = new XmlDocumentationSerializer();

        /// <summary>
        /// Loads the documentation.
        /// </summary>
        /// <returns>
        /// An instance of the <see cref="Documentation"/> class.
        /// </returns>
        public override DocumentationScope LoadDocumentation()
        {
            var documentationScope = new DocumentationScope();

            // Iterate through all XML files in the root folder
            foreach (var documentationStream in GetDocumentationStreams())
            {
                try
                {
                    // Deserialize documentation
                    var loadedDocumentation = xmlDocumentationSerializer.Deserialize(documentationStream);

                    // Merge prototypes
                    loadedDocumentation.MergePrototypes();

                    // Merge the documentation with the rest
                    documentationScope.Documentation.Merge(loadedDocumentation);
                }
                catch (XmlException)
                {
                }
                finally
                {
                    if (documentationStream != null)
                        documentationStream.Dispose();
                }
            }

            return documentationScope;
        }

        /// <summary>
        /// Gets the streams containing the XML documentation.
        /// </summary>
        /// <returns>An enumerable collection of <see cref="Stream"/>s.</returns>
        protected abstract IEnumerable<Stream> GetDocumentationStreams();
    }
}